<template>
    <div class="adminRole">
        <el-form ref="formRef" :inline="true" :model="form" class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px]">
            <el-form-item :label="t('map.mapName') + ':'" prop="name">
                <el-input v-model="form.name" :placeholder="t('map.enterMapName')" clearable class="!w-[200px]" />
            </el-form-item>
            <el-form-item :label="t('map.status') + ':'" prop="status">
                <el-select v-model="form.status" clearable>
                    <el-option :label="t('map.all')" :value="''" />
                    <el-option :label="t('map.enable')" :value="1" />
                    <el-option :label="t('map.disable')" :value="0" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :icon="useRenderIcon(Search)" :loading="loading" @click="onSearch">
                    {{ t('map.search') }}
                </el-button>
                <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
                    {{ t('map.reset') }}
                </el-button>
            </el-form-item>
        </el-form>

        <PureTableBar :title="t('map.mapManagement')" :columns="columns" @refresh="onSearch"
            style="height: calc(100vh - 200px)" v-if="tableHtml">
            <template #buttons>
                <!-- <el-button type="success" :icon="useRenderIcon(AddFill)" @click="pureMap.operateDrawer(true)">
          交管设置
        </el-button> -->

                <el-button type="primary" :icon="useRenderIcon(AddFill)" @click="openDialog()">
                    {{ t('map.addMap') }}
                </el-button>

                <!-- 上传组件 -->
                <el-upload class="upload" accept=".xmap" :show-file-list="false" :http-request="uploadMap"
                    ref="uploadRef">
                </el-upload>
            </template>
            <template v-slot="{ size, dynamicColumns }">
                <pure-table ref="tableRef" adaptive align-whole="center" row-key="Id" showOverflowTooltip
                    table-layout="auto" :loading="loading" :data="dataList" :columns="dynamicColumns"
                    :header-cell-style="{
                        background: 'var(--el-fill-color-light)',
                        color: 'var(--el-text-color-primary)'
                    }" @page-size-change="handleSizeChange" @page-current-change="handleCurrentChange">
                    <template #operation="{ row }">
                        <el-button type="success" link :icon="useRenderIcon(Refresh)" @click="getMapID(row)">{{
                            t('map.importMap') }}
                        </el-button>
                        <el-button class="reset-margin" link type="primary" :size="size" :icon="useRenderIcon(EditPen)"
                            @click="openDialog('编辑', row)">
                            {{ t('map.edit') }}
                        </el-button>
                        <el-button class="reset-margin" link type="danger" :size="size"
                            :icon="useRenderIcon(outlineDelete)" @click="handleDelete(row)">
                            {{ t('map.delete') }}
                        </el-button>
                    </template>
                </pure-table>

                <!-- 地图交管组件 -->
                <!-- <div class="mapCross">
          <div class="mapCorrd">
            <p>x:{{mouseCorrd.x}},y:{{mouseCorrd.y}}</p>
          </div>
          <div id="canvasMap" ref="map"></div>
        </div> -->
            </template>
        </PureTableBar>

        <el-dialog v-model="centerDialogVisible" :title="t('map.pleaseSelectTheImportType')" width="500" center>
            <div>
                <el-radio-group v-model="radio">
                    <el-radio label="1" size="large">科聪地图</el-radio>
                    <el-radio label="2" size="large">睿芯行地图</el-radio>
                </el-radio-group>
                <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" status-icon :rules="rules"
                    label-width="auto" class="demo-ruleForm" v-show="radio === '2'">
                    <el-form-item :label="t('map.agvAddress')" prop="agvIP">
                        <el-input v-model="ruleForm.agvIP" autocomplete="off" />
                    </el-form-item>
                    <el-form-item :label="t('map.portNumber')" prop="port">
                        <el-input v-model="ruleForm.port" autocomplete="off" />
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="centerDialogVisible = false">{{ t('map.cancel') }}</el-button>
                    <el-button type="primary" @click="importMapSubmit(ruleFormRef)">
                        {{ t('map.confirm') }}
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { useDept } from "./utils/hook";
import { ref, onMounted, onUnmounted, reactive, watch, nextTick } from "vue";
import { message } from "@/utils/message";
import { ElMessageBox, FormInstance, FormRules } from "element-plus";
import x2js from "x2js";
import analysis from "./utils/analysisMap";
import { ImportMap } from "@/utils/api/dispatch/map";
import type { UploadInstance, UploadProps, UploadRawFile } from "element-plus";
import { initKonvaStage, mouseCorrd } from "@/views/home/components/dxfMap";
import { readFile } from "@/views/home/components/readFile";
// import crossForm from "./crossForm.vue";
import { useMapStoreHook } from "@/store/modules/map";
import axios from "axios";
import convertData from "./utils/dataConversion";
import { useTranslationLang } from "@/layout/hooks/useTranslationLang";
const { locale } = useTranslationLang();
import { useI18n } from "vue-i18n";
const { t } = useI18n();

// iconify-icons
import AddFill from "@iconify-icons/ri/add-circle-line";
import EditPen from "@iconify-icons/ep/edit-pen";
import outlineDelete from "@iconify-icons/ic/outline-delete";
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";

async function fetchData() {
    try {
        const res = await axios.post(
            `http://${ruleForm.agvIP}:${ruleForm.port}/rbrainrobot/request_node_info`
        );
        if (res.data.msg === "ok") {
            let data = convertData(res, mapid.value);
            ImportMap(data).then(res => {
                if (res.Code === 0) {
                    message(`地图文件导入成功`, {
                        type: "success"
                    });
                }
            });
        } else {
            message(`导入失败:${res.data.error_info}`, { type: "error" });
        }
    } catch (error) {
        message(`请求失败,找不到网址`, { type: "error" });
        console.error("Error fetching data:", error);
    }
}

const ruleFormRef = ref<FormInstance>();
const validatePass = (rule: any, value: any, callback: any) => {
    if (value === "") {
        callback(new Error("请输入AGV地址"));
    } else {
        if (ruleForm.port !== "") {
            if (!ruleFormRef.value) return;
            ruleFormRef.value.validateField("port");
        }
        callback();
    }
};
const validatePass2 = (rule: any, value: any, callback: any) => {
    if (value === "") {
        callback(new Error("请输入端口号"));
    } else {
        callback();
    }
};

const ruleForm = reactive({
    agvIP: "",
    port: ""
});

const rules = reactive<any>({
    agvIP: [{ validator: validatePass, trigger: "blur" }],
    port: [{ validator: validatePass2, trigger: "blur" }]
});

const formRef = ref();
const uploadRef = ref<UploadInstance>();

var mapid = ref(null);
var map = ref();
const pureMap = useMapStoreHook();

var formInline = {
    name: "",
    status: 1,
    stationList: [{}],
    note: "",
    type: 1,
    stationids: []
};

// 对话框开关
const centerDialogVisible = ref(false);
// 单选框
let radio = ref("1");
// 导入地图
function getMapID(row: any) {
    mapid.value = row.id;
    if (row.import === 1) {
        ElMessageBox.confirm(
            t('map.promptText'),
            t('map.prompt'),
            {
                confirmButtonText: t('map.confirm'),
                cancelButtonText: t('map.cancel'),
                type: "warning",
                center: true
            }
        )
            .then(() => {
                centerDialogVisible.value = true;
                // uploadRef.value.$el.querySelector('input').click()
            })
            .catch(() => { });
    } else {
        centerDialogVisible.value = true;
        // uploadRef.value.$el.querySelector('input').click()
    }
}
// 对话框确定
const importMapSubmit = (formEl: FormInstance | undefined) => {
    if (radio.value === "1") {
        uploadRef.value.$el.querySelector("input").click();
        centerDialogVisible.value = false;
    } else if (radio.value === "2") {
        if (!formEl) return;
        formEl.validate(valid => {
            if (valid) {
                // console.log('submit!')
                fetchData();
                centerDialogVisible.value = false;
            } else {
                console.log("error submit!");
            }
        });
    }
};

// 导入地图
function uploadMap(options: any): any {
    // 读取文件
    var file = options.file;
    // 创建FileReader对象
    const reader: any = new FileReader();
    // 以文本形式读取文件
    reader.readAsText(file);

    reader.onload = (e: any) => {
        // 将 XML 数据转换为 JSON 对象
        var x2jss = new x2js();
        // 将xml转换为js对象
        const xml = x2jss.xml2js(reader?.result);
        // 分析xml对象，获取数据
        const data = analysis(xml, mapid.value);
        // console.log("data=>", data);
        // data.roadList = data.roadList.slice(0, 100)
        // data.stationList = data.stationList.slice(0, 100)
        // console.log("data2=>", data);
        // exportToJsonFile(data, 'map.json');

        // 导入地图数据
        ImportMap(data).then(res => {
            // 如果导入成功
            if (res.Code === 0) {
                // 弹出成功提示
                message(`地图文件导入成功`, {
                    type: "success"
                });
            }
        });
    };
}

function exportToJsonFile(data, filename) {
    // 将对象转换为JSON字符串
    const jsonString = JSON.stringify(data, null, 2);

    // 创建Blob对象
    const blob = new Blob([jsonString], { type: 'application/json' });

    // 创建下载链接
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename || 'data.json';

    // 触发下载
    document.body.appendChild(a);
    a.click();

    // 清理
    setTimeout(() => {
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }, 0);
}

// onMounted(()=>{
//   readFile().then(data => {
//     initKonvaStage('canvasMap', map, data, true)
//   })
// })

// onUnmounted(()=>{
//   pureMap.clearCross()
// })

const tableHtml = ref(true);

watch(() => locale.value, (val) => {
    tableHtml.value = false
    nextTick(() => {
        tableReloading()
        tableHtml.value = true
    })
})

const {
    columns,
    loading,
    dataList,
    openDialog,
    handleDelete,
    form,
    onSearch,
    resetForm,
    pagination,
    handleSizeChange,
    handleCurrentChange,
    tableReloading
} = useDept();
</script>

<style lang="scss" scoped>
.upload {
    display: inline-block !important;
    height: 20px;
    vertical-align: middle;
}

.search-form {
    :deep(.el-form-item) {
        margin-bottom: 12px;
    }
}

.mapCross {
    position: relative;
    height: calc(100% - 260px);
    background: linear-gradient(90deg, rgb(62 61 61 / 40%) 2%, transparent 0%) 0 0,
        linear-gradient(180deg, transparent 99%, rgb(62 61 61 / 40%) 1%) 0 0;
    background-color: #001529;
    background-size: 50px 50px;

    // #canvasMap {
    //     width: 100%;
    //     height: 100%;
    // }
}

.pure-table {
    height: 200px;
    overflow: hidden;
}
</style>
